#!/bin/bash

# 设置仓库目录
REPO_DIR="/app"
REMOTE_REPO="https://gitee.com/yyned2501/confirmation.git"
REMOTE_BRANCH="master" # 替换为你的远程分支名，例如 "main"

chown -R root:root $REPO_DIR

# 导航到仓库目录
cd "$REPO_DIR" || {
    echo "Failed to navigate to $REPO_DIR"
    exit 1
}

# 检查是否是一个 Git 仓库
if [ ! -d ".git" ]; then
    echo "Initializing Git repository in $REPO_DIR..."
    git init
    git remote add origin "$REMOTE_REPO"
fi

git checkout master

# 尝试拉取远程仓库的更改
if ! git pull --ff-only origin "$REMOTE_BRANCH"; then
    # 如果拉取失败（可能是因为本地有未提交的更改或冲突），则重置到远程分支的状态
    echo "Local changes detected or conflict during pull. Resetting to remote $REMOTE_BRANCH..."
    git fetch origin "$REMOTE_BRANCH"
    git reset --hard origin/"$REMOTE_BRANCH"

    # 再次尝试拉取，但这次应该不会有问题（因为我们已经重置到远程分支的状态了）
    if git pull origin "$REMOTE_BRANCH"; then
        echo "Repository updated successfully after reset and pull."
    else
        echo "Failed to pull latest changes after reset."
        exit 1
    fi
else
    echo "Repository updated successfully."
fi
